/* requestHandler = {
    params: {},
    success: function (res) {
        // success
    },
    fail: function () {
        // fail
    },
}*/

//GET请求
function GET(API_URL, requestHandler) {
    requestLoading('GET', API_URL, requestHandler, {'content-type': 'application/json'}, "");
}

function headerGET(API_URL, header, requestHandler) {
    requestLoading('GET', API_URL, requestHandler, header, "");
}

//POST请求
function POST(API_URL, requestHandler) {
    requestLoading('POST', API_URL, requestHandler, {"content-type": "application/x-www-form-urlencoded"}, "");
}

function headerPOST(API_URL, header, requestHandler) {
    requestLoading('POST', API_URL, requestHandler, header, "");
}

function requestLoading(method, API_URL, requestHandler, header, message) {
    wx.showNavigationBarLoading();
    if (message != "") {
        wx.showLoading({
            title: message
        });
    }
    //注意：可以对params加密等处理
    var params = requestHandler.params;
    wx.request({
        url: API_URL,
        data: params,
        method: method, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        // header: {}, // 设置请求的 header
        header: header,
        success: function success(res) {
            //console.log(res.data)
            wx.hideNavigationBarLoading();
            if (message != "") {
                wx.hideLoading();
            }
            if (res.statusCode == 200) {
                //注意：可以对参数解密等处理
                requestHandler.success(res.data);
            } else {
                wx.hideNavigationBarLoading();
                if (message != "") {
                    wx.hideLoading();
                }
                requestHandler.fail();
            }
        },
        fail: function fail() {
            wx.hideNavigationBarLoading();
            if (message != "") {
                wx.hideLoading();
            }
            requestHandler.fail();
        },
        complete: function complete() {
            // complete
        }
    });
}

module.exports = {
    GET: GET,
    POST: POST,
    headerGET: headerGET,
    headerPOST: headerPOST,
    requestLoading: requestLoading
};